#!/usr/bin/env python
# encoding: utf-8

from werkzeug.security import generate_password_hash
from werkzeug.security import check_password_hash
from flask_login import UserMixin
import pymysql
from demo.mysql_demo import create_cursor
import uuid


class User(UserMixin):
    id = None
    password_hash = None

    def __init__(self, username):
        self.username = username

        if self.username is not None:
            with create_cursor() as (conn, cursor):
                try:
                    cursor.execute('SELECT gid, pwd_hash FROM umc.user WHERE name=%s', self.username)
                    record = cursor.fetchone()
                    if record is not None:
                        self.id = record.get('gid')
                        self.password_hash = record.get('pwd_hash')

                except pymysql.MySQLError:
                    pass

        if self.id is None:
            self.id = str(uuid.uuid4())

    @property
    def password(self):
        raise AttributeError('password is not a readable attribute')

    @password.setter
    def password(self, password):
        """save user name, id and password hash to json file"""
        self.password_hash = generate_password_hash(password)
        with create_cursor() as (conn, cursor):
            try:
                conn.begin()
                sql = 'INSERT INTO umc.user (`gid`, `name`, `pwd_hash`) VALUES (%s, %s, %s)'
                cursor.execute(sql, (self.id, self.username, self.password_hash))
                conn.commit()
            except pymysql.MySQLError:
                conn.rollback()

    def verify_password(self, password):
        if self.password_hash is None:
            return False
        return check_password_hash(self.password_hash, password)

    @staticmethod
    def get(user_id):
        """try to return user_id corresponding User object.
        This method is used by load_user callback function
        """
        if not user_id:
            return None

        with create_cursor() as (conn, cursor):
            try:
                cursor.execute('SELECT name FROM umc.user WHERE gid=%s', user_id)
                record = cursor.fetchone()
                if record is not None:
                    return User(record.get('name'))
                return None
            except pymysql.MySQLError:
                return None
